#	Plugin interface
#		methods: search, search_by_ref, init, title, version, desc
#
#
#
#	Grabber plugin
#		Tvrage
#
#		
#

use modules::MythTV;
use HTML::Parser;
use HTML::TreeBuilder;
use HTML::Entities;
use LWP::Simple;
use LWP::UserAgent;
use Getopt::Long;
use File::Spec;
use Text::Levenshtein qw(distance);

package grabbers::tvrage;

my $_rev = '$Rev: 178 $';

# Exports
our $VERSION = "1.1";
sub title
{
	return "Tvrage";
}
sub desc
{
	return "Search on www.tvrage.com";
}
sub version
{
	$_rev =~ s/\$//g;
	return $VERSION.", ".$_rev ;
}
#end Exports


sub search 
{
	my $self = shift;
	my $title = shift;
	my $subtitle = shift;
	my $season = shift;
	my $episode = shift;
	my %details;	

	if( length $season == 0  && length $episode == 0 )
	{
		print " Not a TV show\n";
	}
	else
	{
		if( length $season == 0)
		{
			# if no season info, then assume it is season 1
			$season = 1;
		}
		$result = get_show(\%details, $title, $subtitle, $season, $episode, 0);
	}

	if(length $details{Subtitle} >0)
	{
#		print "success";
		#if(length $details->{Postmatch} > 0)
		#{
			# Compare subtitle with postmatch for posible
			#   numbering error
		#	$likeness = comparestrings($parsing_details->{Postmatch}, $file_details->{Subtitle});
		#	if($likeness < 80)
		#	{
		#		print ", not happy\n Wanted \"".$parsing_details->{Postmatch}."\" got \"".$file_details->{Subtitle}."\"\n";
		#		# Look for a file that has the subtitle in it, ignore if can't find one
		#		if(findfile($file_details->{Subtitle},$parsing_details->{'filename'},$rFiles))
		#		{
		#			print " Found a file that might contain ".$file_details->{Subtitle}."\n";
		#			print " Trying harder...\n";
		#			if(getTvRageEpisodeNum($result->{ShowUrl}, $parsing_details->{Postmatch},\$parsing_details) == 1)
		#			{
		#				print " Found better episode details...\n";
		#				$result = get_show(\$parsing_details, \$file_details);
		#			}
		#		}
		#	}
		#	else
		#	{
		#		print "\n";
		#	}
		#}
		#else
		#{
		#	print "\n";
		#}
	}
	if(length $details{Subtitle} >0)
	{
		getTVRageData(\%details, $result->{ShowUrl},$result->{EpisodeUrl});
	}

	return %details;
}

sub search_by_ref
{
	my $ref = shift;
	my $details;	
	return $details;
}

sub init
{
}

sub new
{
    my($class, %args) = @_;
    my $self = bless({}, $class);
    
    init();
    
    return $self;
}
#######################################
##   UTILITIES
#######################################
#conduct a quick search on TvRage.com
sub get_show {
	my $file_details = shift;
	my $title = shift;
	my $subtitle = shift;
	my $season = shift;
	my $episode = shift;
	my $year = shift;
		
	my $result;
	my $Search;
	if( $year != 0 )
	{
		$Search = $title."_".$year;
	}
	else
	{
		$Search = $title;
	}
	my $se_ep = $season."x".$episode;
	if ( $title ne "" )
	{
		my $site = LWP::Simple::get("http://services.tvrage.com/tools/quickinfo.php?show=".$Search."&ep=".$se_ep."&exact=1");
		if(!(defined($site)))
		{
			print "Tvrage lookup failed, trying again in 5 seconds...\n";
			sleep(5);
			$site = LWP::Simple::get("http://services.tvrage.com/tools/quickinfo.php?show=".$Search."&ep=".$se_ep);
		}
		if(!(defined($site)))
		{
			print "tvrage lookup failed: ".$Search." ".$se_ep."\n";
		}
		foreach $line (split("\n",$site) )
		{
			my ($sec,$val) = split('\@',$line,2);
			if ($sec eq "Show Name" )
			{
				$file_details->{Title} = $val;
			}
			elsif ( $sec eq "Show URL" )
			{
				$result->{ShowUrl} = $val;
			}
			elsif ( $sec eq "Premiered" )
			{
				$file_details->{Year} = $val;
			}
			elsif ($sec eq "Country" )
			{
				$file_details->{Country} = $val;
			}
			elsif ( $sec eq "Status" )
			{
				$file_details->{Status} = $val;
			}
			elsif ( $sec eq "Classification" )
			{
				$file_details->{Classification} = $val;
			}
			elsif ( $sec eq "Runtime" )
			{
				$file_details->{Length} = $val;
			}
			elsif ( $sec eq "Latest Episode" )
			{
				my($ep,$title,$airdate) = split('\^',$val);
				$file_details->{LatestEpisode} = $ep.", \"".$title."\" aired on ".$airdate;
			}
			elsif ( $sec eq "Next Episode" )
			{
				my($ep,$title,$airdate) = split('\^',$val);
				$file_details->{NextEpisode} = $ep.", \"".$title."\" airs on ".$airdate;
			}
			elsif ( $sec eq "Episode Info" )
			{
				my($ep_num,$ep_title,$airdate) = split('\^',$val);
				my($se,$ep) = split('x',$ep_num);
				$file_details->{Episode} = int($ep);
				$file_details->{Season} = int($se);
				$file_details->{Subtitle} = $ep_title;
				($file_details->{Year}) = $airdate =~ m/\d*\/\w*\/(\d*)/;
			}
			elsif ( $sec eq "Episode URL" )
			{
				$result->{EpisodeUrl} = $val;
			}
		}
	}
	return $result;
}

sub getTvRageEpisodeNum
{
	my $showURL = shift;
	my $episodeTitle = shift;
	my $file_details = shift;

	my $bestScore= "-1000";
	my $bestCode="NA";
	my $result = 0;
	my $text;

	$showURL = $showURL."/episode_list/all";

	print "Searching for [".$episodeTitle."] at ".$showURL."\n";

	if( $cache_tvrage_epi_list_url ne $showURL)
	{
		$cache_tvrage_epi_list_url = $showURL;
		my $ua = new LWP::UserAgent(agent => 'Firefox');
		my $epiListHTML = $ua->request(HTTP::Request->new(GET => $showURL));
		my $epiListParser = new HTML::TreeBuilder;
		$cache_tvrage_epi_list_doc = $epiListParser->parse($epiListHTML->content);
		$cache_tvrage_epi_list_doc->objectify_text();
	}

	my @epiList = $cache_tvrage_epi_list_doc->look_down("_tag","td","style","padding-left: 6px;");

	foreach my $episodeLink (@epiList)
	{
		my @epiTitle = $episodeLink->look_down("_tag","~text");
		foreach my $string (@epiTitle)
		{
			$text = $string->attr_get_i('text');
			$score = comparestrings($text, $episodeTitle);
			
			if($score > $bestScore)
			{
				$bestScore = $score;
				$URL = $string->look_up("_tag","a");
				if( $URL != undef)
				{
					$bestCode = $URL->attr_get_i("href");
					$bestCode =~ s/.*(\d\dx\d\d)$/\1/;
				}
				else
				{
					print "ERROR: bad $URL\n";
				}
			}
		}
	}
	if($bestScore > 85)
	{
		$file_details->{Season} = $bestCode;
		$file_details->{Season} =~ s/(\d\d)x\d\d/\1/;

		$file_details->{Episode} = $bestCode;
		$file_details->{Episode} =~ s/\d\dx(\d\d)/\1/;

		$file_details->{Season} =~ s/^0//;
		$file_details->{Episode}=~ s/^0//;
		$result = 1;
	}
	return $result;
}

sub getTVRageData {
	my $file_details = shift(@_);
	my $showURL = shift(@_)."?remove_add=1";
	my $episodeURL = shift(@_)."?remove_add=1";
	
	if($cache_tvrage_epi_detail_url ne $episodeURL)
	{
		$cache_tvrage_epi_detail_url = $episodeURL;
		my $ua = new LWP::UserAgent(agent => 'Firefox');
		my $episodeHTML = $ua->request(HTTP::Request->new(GET => $episodeURL));
		my $episodeParser = new HTML::TreeBuilder;

		$cache_tvrage_epi_detail_doc = $episodeParser->parse($episodeHTML->content);
		$cache_tvrage_epi_detail_doc->objectify_text();
	}
	if($cache_tvrage_title_detail_url ne $showURL)
	{
		$cache_tvrage_title_detail_url = $showURL;

		my $ua = new LWP::UserAgent(agent => 'Firefox');
		my $showHTML = $ua->request(HTTP::Request->new(GET => $showURL));
		my $showParser = new HTML::TreeBuilder;

		$cache_tvrage_title_detail_doc = $showParser->parse($showHTML->content);
		$cache_tvrage_title_detail_doc->objectify_text();
	}


	my @episodeData = $cache_tvrage_epi_detail_doc->look_down("_tag","~text");

	$file_details->{Director} = getTVRageSection(\@episodeData, "Director: ");
	$file_details->{Director} =~ s/\(\d\)//g;
	$desc = getTVRageSection(\@episodeData, "Episode Summary");
	$file_details->{Plot}=$desc;

	$file_details->{PosterUrl}=getTVRageTitleImage($cache_tvrage_title_detail_doc);
	$file_details->{ScreenshotUrl}=getTVRageEpisodeImage($cache_tvrage_epi_detail_doc);

}

sub getTVRageSection
{
	my $block = shift;
	my $search = shift;
	my $result = "";
	my $stage=0;
	my $first_string = "";
	foreach my $section (@{$block})
	{
		if($stage == 0)
		{
			if($section->attr_get_i('text') eq "Episode Information")
			{
				$stage =1;
			}
		}
		elsif($stage == 1)
		{
			if($section->attr_get_i('text') eq $search)
			{
				$stage = 2;
			}
		}
		elsif($stage == 2)
		{
			$text = $section->attr_get_i('text');
			# &nbsp; get translated to 240 0ctal
			if( $text =~ /\240/ )
			{
				$result = "";
				$stage =3;
			}
			elsif( $text =~ /\w+:\s?$/)
			{
				last;
			}
			else
			{
				$result = $result.$text;
			}
		}
		elsif($stage == 3)
		{
			$text = $section->attr_get_i('text');
			$text =~ s/&#ldquo;//g;
			$text =~ s/&#rdquo;//g;
			if( $text =~ /\240/ )
			{
				last;
			}
			elsif(!$section->is_inside('script'))
			{
				$result = $result.$text;
#				last;
			}
		}
	}
	return $result;
}

sub getTVRageTitleImage
{
	my $doc = shift;
	my $url;
	$hits = $doc->look_down("_tag","img","src",qr/http\:\/\/images\.tvrage\.(com|net)\/shows.*/);
	if($hits)
	{
		$url = $hits->attr_get_i('src');
	}
	else
	{
		$url = "";
	}
	return $url;
}

sub getTVRageEpisodeImage
{
	my $doc = shift;
	my $url;
	$hits = $doc->look_down("_tag","img","src",qr/http\:\/\/images\.tvrage\.(com|net)\/screencaps.*/);
	if($hits)
	{
		$url = $hits->attr_get_i('src');
	}
	else
	{
		$url = "";
	}
	return $url;
}

sub comparestrings
{
	my $first = shift;
	my $second = shift;
	my $likeness;
	# make the comparison a little easier by removing
	# qutoes commas etc, plus make both string upper case.
	# Convert single digits to words
	$first = digit2str($first);	
	$second = digit2str($second);	
	$first = uc($first);
	$second = uc($second);
	$first =~ s/[^\w\s]//g;
	$second =~ s/[^\w\s]//g;
	$leven_distance = distance($first, $second);
	my $totallen = length($first) + length($second);
	return (($totallen - $leven_distance) / $totallen) * 100;
}

sub digit2str
{
	my $phrase = shift;
	$phrase =~ s/\D1\D/one/g; 
	$phrase =~ s/\D2\D/two/g; 
	$phrase =~ s/\D3\D/three/g; 
	$phrase =~ s/\D4\D/four/g; 
	$phrase =~ s/\D5\D/five/g;
	$phrase =~ s/\D6\D/six/g; 
	$phrase =~ s/\D7\D/seven/g; 
	$phrase =~ s/\D8\D/eight/g; 
	$phrase =~ s/\D9\D/nine/g; 
	$phrase =~ s/\D10\D/ten/g; 
	return $phrase;
}

1;
